<template>
  <div class="login-log">
    <el-page-header title="日志管理">
      <template #content>
        <span class="page-header-content">登录日志</span>
      </template>
    </el-page-header>

    <div class="log-content">
      <!-- 搜索栏 -->
      <el-card class="search-card">
        <el-form :model="searchForm" ref="searchFormRef" inline>
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="searchForm.username"
              placeholder="请输入用户名"
              clearable
            />
          </el-form-item>
          <el-form-item label="登录状态" prop="status">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择登录状态"
              clearable
              style="width: 160px"
            >
              <el-option label="成功" value="0" />
              <el-option label="失败" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="登录方式" prop="loginType">
            <el-select
              v-model="searchForm.loginType"
              placeholder="请选择登录方式"
              clearable
              style="width: 160px"
            >
              <el-option label="账号密码" value="0" />
              <el-option label="手机验证码" value="1" />
              <el-option label="扫码登录" value="2" />
              <el-option label="第三方登录" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="登录时间" prop="timeRange">
            <el-date-picker
              v-model="searchForm.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              :shortcuts="dateShortcuts"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="success" @click="handleExport">导出日志</el-button>
            <el-button type="danger" @click="handleCleanLog">清空日志</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 日志表格 -->
      <el-card class="table-card">
        <div class="table-header">
          <div class="left">
            <el-button 
              type="danger" 
              :disabled="selectedIds.length === 0" 
              @click="handleDeleteSelected"
            >
              批量删除
            </el-button>
          </div>
        </div>
        
        <el-table
          :data="tableData"
          style="width: 100%"
          v-loading="loading"
          border
          stripe
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="userName" label="用户名" width="120">
            <template #default="scope">
              <el-tooltip
                :content="scope.row.userInfo || scope.row.userName"
                placement="top"
                effect="light"
              >
                <span>{{ scope.row.userName }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="ipaddr" label="登录IP" width="140" />
          <el-table-column prop="loginLocation" label="登录地点" width="160" />
          <el-table-column prop="browser" label="浏览器" width="120" />
          <el-table-column prop="os" label="操作系统" width="120" />
          <el-table-column prop="loginType" label="登录方式" width="120">
            <template #default="scope">
              <el-tag :type="getLoginTypeTag(scope.row.loginType)">
                {{ getLoginTypeLabel(scope.row.loginType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag
                :type="scope.row.status === 0 ? 'success' : 'danger'"
              >
                {{ scope.row.status === 0 ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="loginTime" label="登录时间" width="180" />
          <el-table-column
            v-if="showMsg"
            prop="msg"
            label="消息"
            min-width="200"
            show-overflow-tooltip
          />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="handleViewDetail(scope.row)"
              >
                详情
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <!-- 详情弹窗 -->
      <el-dialog
        v-model="detailVisible"
        title="登录日志详情"
        width="600px"
        destroy-on-close
      >
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户名">
            {{ currentLog.userName }}
          </el-descriptions-item>
          <el-descriptions-item label="登录状态">
            <el-tag :type="currentLog.status === 0 ? 'success' : 'danger'">
              {{ currentLog.status === 0 ? '成功' : '失败' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="登录方式">
            <el-tag :type="getLoginTypeTag(currentLog.loginType)">
              {{ getLoginTypeLabel(currentLog.loginType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="登录时间">
            {{ currentLog.loginTime }}
          </el-descriptions-item>
          <el-descriptions-item label="登录IP">
            {{ currentLog.ipaddr }}
          </el-descriptions-item>
          <el-descriptions-item label="登录地点">
            {{ currentLog.loginLocation }}
          </el-descriptions-item>
          <el-descriptions-item label="浏览器">
            {{ currentLog.browser }}
          </el-descriptions-item>
          <el-descriptions-item label="操作系统">
            {{ currentLog.os }}
          </el-descriptions-item>
          <el-descriptions-item label="用户代理" :span="2">
            {{ currentLog.userAgent }}
          </el-descriptions-item>
          <el-descriptions-item v-if="currentLog.status === 1" label="失败原因" :span="2">
            <div class="error-message">{{ currentLog.msg }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { loginLogApi } from '@/api/monitor'

export default {
  name: 'LoginLog',
  setup() {
    // 搜索表单
    const searchForm = reactive({
      username: '',
      status: '',
      loginType: '',
      timeRange: [],
      pageNum: 1,
      pageSize: 10
    })

    // 日期快捷选项
    const dateShortcuts = [
      {
        text: '最近一小时',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000)
          return [start, end]
        }
      },
      {
        text: '今天',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setHours(0, 0, 0, 0)
          return [start, end]
        }
      },
      {
        text: '最近三天',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
          return [start, end]
        }
      },
      {
        text: '最近一周',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          return [start, end]
        }
      }
    ]

    // 表格数据
    const loading = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const tableData = ref([])
    const selectedIds = ref([])

    // 是否显示消息列
    const showMsg = computed(() => {
      return tableData.value.some(item => item.status === 1)
    })

    // 详情弹窗
    const detailVisible = ref(false)
    const currentLog = ref({})

    // 登录方式标签
    const getLoginTypeTag = (type) => {
      if (type === 0) return ''
      if (type === 1) return 'success'
      if (type === 2) return 'warning'
      if (type === 3) return 'info'
      return 'info'
    }

    // 登录方式文本
    const getLoginTypeLabel = (type) => {
      if (type === 0) return '账号密码'
      if (type === 1) return '手机验证码'
      if (type === 2) return '扫码登录'
      if (type === 3) return '第三方登录'
      return type
    }

    // 获取登录日志列表
    const getLoginLogList = () => {
      loading.value = true
      // 处理时间范围
      const params = { ...searchForm }
      if (params.timeRange && params.timeRange.length === 2) {
        params.startTime = params.timeRange[0]
        params.endTime = params.timeRange[1]
      }
      delete params.timeRange

      loginLogApi.getList(params).then(res => {
        if (res.code === 200) {
          tableData.value = res.data.rows
          total.value = res.data.total
        } else {
          ElMessage.error(res.msg || '获取登录日志列表失败')
        }
        loading.value = false
      }).catch(() => {
        loading.value = false
        ElMessage.error('获取登录日志列表失败')
      })
    }

    // 查询
    const handleSearch = () => {
      searchForm.pageNum = 1
      getLoginLogList()
    }

    // 重置
    const handleReset = () => {
      searchForm.username = ''
      searchForm.status = ''
      searchForm.loginType = ''
      searchForm.timeRange = []
      handleSearch()
    }

    // 导出
    const handleExport = () => {
      ElMessage.success('日志导出成功')
    }

    // 查看详情
    const handleViewDetail = (row) => {
      currentLog.value = row
      detailVisible.value = true
    }

    // 表格选择
    const handleSelectionChange = (selection) => {
      selectedIds.value = selection.map(item => item.id)
    }

    // 删除单条日志
    const handleDelete = (row) => {
      ElMessageBox.confirm('确定要删除该登录日志吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        loginLogApi.deleteLoginLog(row.id).then(res => {
          if (res.code === 200) {
            ElMessage.success('删除成功')
            getLoginLogList()
          } else {
            ElMessage.error(res.msg || '删除失败')
          }
        }).catch(() => {
          ElMessage.error('删除失败')
        })
      }).catch(() => {})
    }

    // 批量删除日志
    const handleDeleteSelected = () => {
      if (selectedIds.value.length === 0) {
        ElMessage.warning('请至少选择一条记录')
        return
      }
      ElMessageBox.confirm(`确定要删除选中的${selectedIds.value.length}条登录日志吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        loginLogApi.deleteLoginLog(selectedIds.value.join(',')).then(res => {
          if (res.code === 200) {
            ElMessage.success('批量删除成功')
            getLoginLogList()
          } else {
            ElMessage.error(res.msg || '批量删除失败')
          }
        }).catch(() => {
          ElMessage.error('批量删除失败')
        })
      }).catch(() => {})
    }

    // 清空日志
    const handleCleanLog = () => {
      ElMessageBox.confirm('确定要清空所有登录日志吗？此操作不可恢复！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        loginLogApi.cleanLoginLog().then(res => {
          if (res.code === 200) {
            ElMessage.success('清空登录日志成功')
            getLoginLogList()
          } else {
            ElMessage.error(res.msg || '清空登录日志失败')
          }
        }).catch(() => {
          ElMessage.error('清空登录日志失败')
        })
      }).catch(() => {})
    }

    // 分页
    const handleSizeChange = (val) => {
      searchForm.pageSize = val
      getLoginLogList()
    }

    const handleCurrentChange = (val) => {
      searchForm.pageNum = val
      getLoginLogList()
    }

    // 组件挂载时获取列表
    onMounted(() => {
      getLoginLogList()
    })

    return {
      searchForm,
      dateShortcuts,
      loading,
      currentPage,
      pageSize,
      total,
      tableData,
      selectedIds,
      showMsg,
      detailVisible,
      currentLog,
      getLoginTypeTag,
      getLoginTypeLabel,
      handleSearch,
      handleReset,
      handleExport,
      handleViewDetail,
      handleSelectionChange,
      handleDelete,
      handleDeleteSelected,
      handleCleanLog,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.login-log {
  padding: 20px;
}

.page-header-content {
  font-size: 20px;
  font-weight: bold;
}

.log-content {
  margin-top: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.error-message {
  color: #f56c6c;
  background-color: #fef0f0;
  padding: 8px;
  border-radius: 4px;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style> 